package com.common.frame.decoration;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * RecyclerView 分割线
 */
public abstract class BaseDecoration extends RecyclerView.ItemDecoration {

    @Override
    abstract public void getItemOffsets(Rect outRect, View view,
                                        RecyclerView parent, RecyclerView.State state);

    @Override
    abstract public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state);

    private Paint paint;
    private Drawable drawable;

    public Paint getPaint() {
        if (paint == null){
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        }
        return paint;
    }

    public void setDrawable(Drawable drawable) {
        this.drawable = drawable;
    }

    protected Rect getViewBoundRect(View view){
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        return new Rect(view.getLeft() - params.leftMargin,
                view.getTop() - params.topMargin,
                view.getRight() + params.rightMargin,
                view.getBottom() + params.bottomMargin);
    }

    protected void drawLeftSpace(Canvas canvas, Rect boundRect, int space){
        if (space == 0){
            return;
        }
        Rect newRect = new Rect(boundRect.left-space, boundRect.top, boundRect.left, boundRect.bottom);
        draw(canvas, newRect);
    }

    protected void drawTopSpace(Canvas canvas, Rect boundRect, int space){
        if (space == 0){
            return;
        }
        Rect newRect = new Rect(boundRect.left, boundRect.top-space, boundRect.right, boundRect.top);
        draw(canvas, newRect);
    }

    protected void drawRightSpace(Canvas canvas, Rect boundRect, int space){
        if (space == 0){
            return;
        }
        Rect newRect = new Rect(boundRect.right, boundRect.top, boundRect.right+space, boundRect.bottom);
        draw(canvas, newRect);
    }

    protected void drawBottomSpace(Canvas canvas, Rect boundRect, int space){
        if (space == 0){
            return;
        }
        Rect newRect = new Rect(boundRect.left, boundRect.bottom, boundRect.right, boundRect.bottom+space);
        draw(canvas, newRect);
    }


    private void draw(Canvas canvas, Rect boundRect){
        if (drawable != null){
            drawable.setBounds(boundRect);
            drawable.draw(canvas);
        }else{
            canvas.drawRect(boundRect, paint);
        }
    }

}
